package org.locker.device.controller.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.locker.common.core.domain.R;
import org.locker.common.core.exception.ServiceException;
import org.locker.common.satoken.utils.LoginHelper;
import org.locker.domain.User;
import org.locker.domain.bo.UserBo;
import org.locker.domain.vo.LoginWxVo;
import org.locker.domain.vo.UserVo;
import org.locker.service.IAuthStrategy;
import org.locker.service.IUserService;
import org.locker.system.domain.vo.SysOssUploadVo;
import org.locker.system.domain.vo.SysOssVo;
import org.locker.system.service.ISysOssService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * (小程序)用户登录
 * @Description:
 * @Author: lark
 * @Date: 2023/10/8
 */

@RequiredArgsConstructor
@RestController
@RequestMapping("/app/user")
@Slf4j
public class WebUserController {

    private final IUserService userService;
    private final WxMaService wxMaService;
    private final ISysOssService ossService;


    /**
     * 查询当前用户信息
     * @param isHide
     * @return
     */
    @GetMapping("/userInfo")
    public R getUserInfo(@RequestParam(required = false,name = "isHide",defaultValue = "true")Boolean isHide){
        Long userId = LoginHelper.getUserId();
        UserVo userVo = userService.queryById(userId);
        if (isHide){
            //手机号与身份证脱敏处理
            userVo.setPhone(ReUtil.replaceAll(userVo.getPhone(), "(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            userVo.setCardNo(ReUtil.replaceAll(userVo.getCardNo(), "(\\d{6})\\d{8}(\\w{4})", "$1****$2"));
        }
        return R.ok(userVo);
    }

    /**
     * 登录接口
     * @param appid appid
     * @param code code
     * @return
     */
    @GetMapping("/login")
    public R login(@RequestParam("appid")String appid,
                   @RequestParam("code")String code) {
        if (!wxMaService.switchover(appid)) {
            throw new ServiceException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            log.info(session.getSessionKey());
            log.info(openid);
            //登录操作
            LoginWxVo login = IAuthStrategy.login(openid);
            Map<Object, Object> build = MapUtil.builder().put("session", session).put("LoginWxVo", login).build();
            return R.ok(build);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return R.fail(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    /**
     * 上传用户头像
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadAvatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysOssUploadVo> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = ossService.upload(file);
        SysOssUploadVo uploadVo = new SysOssUploadVo();
        uploadVo.setUrl(oss.getUrl());
        uploadVo.setFileName(oss.getOriginalName());
        uploadVo.setOssId(oss.getOssId().toString());
        return R.ok(uploadVo);
    }

    /**
     * 修改用户信息
     * @param bo
     * @return
     */
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody UserBo bo){
        Long userId = LoginHelper.getUserId();
        userService.update(Wrappers.<User>lambdaUpdate()
            .set(StrUtil.isNotBlank(bo.getNickname()),User::getNickname,bo.getNickname())
            .set(StrUtil.isNotBlank(bo.getIconUrl()),User::getIconUrl,bo.getIconUrl())
            .set(StrUtil.isNotBlank(bo.getPhone()),User::getPhone,bo.getPhone())
            .eq(User::getUserId,userId));
        return R.ok();
    }
}
